require 'yaml'

include Gosu
include Button
class GameControls

  CONTROLS_FILE = "control_config.yaml"
  attr_reader :sorted_controls

  def initialize(window, input_yaml_file)
    @sorted_controls = [{}, {}, {}, {}]
    @players = [:blue, :red, :green, :purple]
    @window = window
    save_default_inputs(input_yaml_file) if !File.exists?(input_yaml_file)
    load_inputs(input_yaml_file)
  end

  def setControlForPlayer(player, control, button_id)
    @sorted_controls[@players.index(player)][control] = button_id
    # EX: @sorted_controls[1]["Accelerate"] = KbUp  # red accelerates on 'up'
  end

  def self.save_inputs(sorted_controls)
    inputs_file = File.open(CONTROLS_FILE, "w") do |file|
      YAML.dump(sorted_controls, file)
    end
  end

  def self.load_default_inputs
    sorted_controls = [ #umm... get two keyboards. It's gonna be crowded.
     # or you could get a gamepad and customize controls in the menu
      # (or you could get a broken wrist)
      # blue
      {"Accelerate" => KbUp, "Reverse" => KbDown, "Turn Left" => KbLeft,
        "Turn Right" => KbRight, "Shoot" => KbSpace},
      # red
      {"Accelerate" => KbNumpad8, "Reverse" => KbNumpad5, 
        "Turn Left" => KbNumpad4, "Turn Right" => KbNumpad6, 
        "Shoot" => KbEnter},
      # green 
      {"Accelerate" => KbI, "Reverse" => KbK, "Turn Left" => KbJ,
        "Turn Right" => KbL, "Shoot" => KbBackspace},
      # purple
      {"Accelerate" => KbS, "Reverse" => KbX, "Turn Left" => KbZ,
        "Turn Right" => KbC, "Shoot" => KbLeftShift},
    ]
    return sorted_controls
  end

  def self.load_inputs
    if !File.exists? CONTROLS_FILE
      return load_default_inputs
    end
    return File.open(CONTROLS_FILE) {|file| YAML::load(file) }
  end

end
